package com.cndongtai.service.job;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.cndongtai.dao.impl.ChargeCountDao;
import com.cndongtai.dao.impl.DtuDao;
import com.cndongtai.dao.impl.LightChargeCountDao;
import com.cndongtai.dao.impl.LightDao;
import com.cndongtai.dao.impl.LightFirmwareDao;
import com.cndongtai.dao.impl.LightStatusRecordDao;
import com.cndongtai.dao.impl.UserDao;
import com.cndongtai.net.NetController;
import com.cndongtai.po.ChargeCount;
import com.cndongtai.po.Dtu;
import com.cndongtai.po.Light;
import com.cndongtai.po.LightChargeCount;
import com.cndongtai.po.LightFirmware;
import com.cndongtai.po.LightStatusRecord;
import com.cndongtai.po.User;
import com.cndongtai.service.firmware.LightFirmwareService;
import com.cndongtai.service.net.NetService;
import com.cndongtai.util.DateUtil;

@Service("taskJob")
public class TaskJob {
	
	public final Logger log = Logger.getLogger(this.getClass());
	
	@Resource(name="userDao")
	private UserDao userDao;
	
	@Resource(name="lightStatusRecordDao")
	private LightStatusRecordDao lightStatusRecordDao;
	
	@Resource(name="chargeCountDao")
	private ChargeCountDao chargeCountDao;
	
	@Resource(name="lightChargeCountDao")
	private LightChargeCountDao lightChargeCountDao;
	
	@Resource(name="dtuDao")
	private DtuDao dtuDao;
	
	@Resource(name="lightDao")
	private LightDao lightDao;
	
	@Resource(name="lightFirmwareDao")
	private LightFirmwareDao lightFirmwareDao;
	
	@Resource(name="netService")
	private NetService netService;
	
	@Resource(name="lightFirmwareService")
	private LightFirmwareService lightFirmwareService;
	
	/**
	 * 充电总数统计
	 */
	public void chargeCountJob() {
		log.info("=========chargeCountJob====START===");
		// 获取所有的用户
		List<User> userList = userDao.queryUserList();
		if(userList==null || userList.size()==0) {
			return;
		}
		
		for(User user : userList) {
			if("admin".equals(user.getUsername())) {
				continue;
			}
			
			// 获取今天该用户下所有设备充电总数
			int todayChargeCount = lightStatusRecordDao.queryLightChargeCountByUserId(user.getUserId());
			
			if(todayChargeCount<=0) {
				continue;
			}
			
			ChargeCount chargeCount = chargeCountDao.queryChargeCountByUserId(user.getUserId());
			if(chargeCount==null) {
				// 插入
				chargeCount = new ChargeCount();
				chargeCount.setUserId(user.getUserId());
				chargeCount.setChargeCount(todayChargeCount);
				chargeCountDao.addChargeCount(chargeCount);
			}else {
				// 更新
				chargeCount.setChargeCount(todayChargeCount);
				chargeCountDao.updateChargeCount(chargeCount);
			}
			
		}
		log.info("=========chargeCountJob====END===");
	}
	
	public void changeOnlineStateJob() {
		log.info("=========changeOnlineStateJob====START===");
		Set<String> keys = NetController.onlineMap.keySet();
		for(String key : keys) {
			Long time = NetController.onlineMap.get(key);
			Dtu dtu = dtuDao.queryDtuByPanId(key);
			if(dtu==null) {
				continue;
			}
			
			if((System.currentTimeMillis()-time)>1000*60*10) {
				// 掉线
				if(dtu.getOnlineState().equals(0)) {
					dtuDao.changeOnlineState(dtu.getDtuId(), 1);
				}
				NetController.onlineMap.remove(key);
			}else if((System.currentTimeMillis()-time)<1000*60*2) {
				if(dtu.getOnlineState().equals(1)) {
					dtuDao.changeOnlineState(dtu.getDtuId(), 0);
				}
			}
		}
		
		log.info("=========changeOnlineStateJob====END===");
	}
	
	/**
	 * 每天凌晨1点开始计算前一天的每个设备的充电电量
	 */
	public void lightChargeCountJob() {
		log.info("=========lightChargeCountJob====START===");
		// 获取所有light
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1);
		
		// 当前时间参数获取
		String dateStr = DateUtil.timeShortFormat(calendar.getTime());
		String startTime = dateStr + " 00:00:00";
		String endTime = dateStr + " 23:59:59";
		String sixTimeStr = dateStr + " 18:00:00";
		Date sixTime = null;
		try {
			sixTime = DateUtil.parseDateFull(sixTimeStr);
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return;
		}
		
		// 前一天时间参数获取
		Calendar calendarBefore = Calendar.getInstance();
		calendarBefore.add(Calendar.DATE, -2);
		
		String dateBeforeStr = DateUtil.timeShortFormat(calendarBefore.getTime());
		String beforeStartTime = dateBeforeStr + " 18:00:00";
		String beforeEndTime = dateBeforeStr + " 23:59:59";
		
		List<Dtu> dtuList = dtuDao.queryDtuList();
		if(dtuList==null) {
			return;
		}
		
		// 根据项目编号进行遍历
		for(Dtu dtu : dtuList) {
			List<Light> lightList = lightDao.queryLightListByDtuId(dtu.getDtuId());
			if(lightList==null) {
				return;
			}

			// 遍历计算light的前天充电电量
			for(Light light : lightList) {
				List<LightStatusRecord> lightStatusRecordList = lightStatusRecordDao.queryLightStatusRecordListByLightId(startTime, endTime, (long)light.getLightId());
				
				if(lightStatusRecordList==null || lightStatusRecordList.size()==0) {
					continue;
				}
				
				LightStatusRecord firstRecord = lightStatusRecordList.get(0);
				int chargeCount = 0;
				
				if(lightStatusRecordList.size()==1) {
					// 判断这个状态的采集时间点，如果该时间点的在6点之前，则放弃
					if(firstRecord.getCollectTime().compareTo(sixTime)<0) {
						continue;
					}
					
					// 获取上一天的电量
					List<LightStatusRecord> beforeLightStatusRecordList = lightStatusRecordDao.queryLightStatusRecordListByLightId(beforeStartTime, beforeEndTime, (long)light.getLightId());
					if(beforeLightStatusRecordList==null || beforeLightStatusRecordList.size()==0) {
						continue;
					}
					
					LightStatusRecord beforeLightStatusRecord = beforeLightStatusRecordList.get(beforeLightStatusRecordList.size()-1);
					
					chargeCount = firstRecord.getChargeCount()-beforeLightStatusRecord.getChargeCount();
				}else {
					// 状态采集点多的时候自动首尾相减
					LightStatusRecord lastRecord = lightStatusRecordList.get(lightStatusRecordList.size()-1);
					chargeCount = lastRecord.getChargeCount()-firstRecord.getChargeCount();
				}
				
				LightChargeCount lightChargeCount = new LightChargeCount();
				lightChargeCount.setLightId(light.getLightId());
				lightChargeCount.setLightNum(light.getLightNum());
				lightChargeCount.setDtuId(dtu.getDtuId());
				lightChargeCount.setPanId(dtu.getPanId());
				lightChargeCount.setUserId(dtu.getCreateBy());
				lightChargeCount.setChargeDay(calendar.getTime());
				lightChargeCount.setChargeCount(chargeCount);
				
				lightChargeCountDao.addLightChargeCount(lightChargeCount);
			}
		}
		log.info("=========lightChargeCountJob====END===");
	}
	
	public void scanLightFirmware() {
		log.info("=========scanLightFirmware====START===");
		// 获取所有路灯信息
		List<Dtu> dtuList = dtuDao.queryDtuList();
		if(dtuList==null || dtuList.size()<1) {
			return;
		}
		
		String uploadType = "22";// 目前仅支持升级控制模块
		for(Dtu dtu : dtuList) {
			List<Light> lightList = lightDao.queryLightListByDtuId(dtu.getDtuId());
			
			for(Light light : lightList) {
				// 获取light的固件信息
				LightFirmware lightFirmware = netService.readDeviceFirmwareInfo(dtu.getPanId(), light.getLightNum(), uploadType);
				if(lightFirmware==null) {
					continue;
				}
				
				lightFirmware.setLightId(light.getLightId());
				lightFirmware.setLastUptTime(new Date());
				
				lightFirmwareService.addOrUpdateLightFirmware(lightFirmware);
			}
		}
		log.info("=========scanLightFirmware====END===");
	}

}
